<template>
  <div style="margin-top: 30px"></div>
  <a-row>
    <a-col :span="5" :offset="1">
      <a-input-search
          style="width: 280px"
          v-model:value="searchValue"
          placeholder="请输入分类名称"
          :loading="searchLoading"
          enter-button
          size="large"
          @search="search"
      />
    </a-col>
    <a-col :span="3" :offset="1">
      <a-button type="primary" size="large" @click="add">新增</a-button>
    </a-col>
  </a-row>
  <a-table :columns="columns"
           :data-source="categorys"
           :row-key="record => record.id"
           :loading="loading"
           :pagination="false"
        >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'cover'">
        <img class="cover" :src="record.cover" />
      </template>
      <template v-else-if="column.key === 'action'">
        <a-space>
          <a-button type="primary" @click="edit(record)">编辑</a-button>
          <a-popconfirm title="确认要删除吗？" @confirm="remove(record.id)">
            <template #icon><question-circle-outlined style="color: red" /></template>
            <a-button type="primary" danger>删除</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
  </a-table>

  <!-- 新增 -->
  <a-modal v-model:visible="visible" :title="title" :footer="null" :maskClosable="false">
    <a-form :model="category"
            :rules="rules"
            ref="myForm"
            @finish="handleOk"
      >
      <a-form-item label="名称" name="name">
        <a-input v-model:value="category.name" placeholder="请输入分类名称" />
      </a-form-item>

      <a-form-item label="父分类" name="parent">
        <a-select
            v-model:value="category.parent"
            show-search
            placeholder="请选择父分类"
            style="width: 200px"
            :options="searchOptions"
            :field-names="{ label: 'name', value: 'id'}"
            :filter-option="filterOption"
        ></a-select>

      </a-form-item>
      <a-form-item label="顺序" name="sort">
        <a-input v-model:value="category.sort" placeholder="请输入分类顺序" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">提交</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { SmileOutlined, DownOutlined,QuestionCircleOutlined } from '@ant-design/icons-vue';
import { ref } from "vue";
import axios from "axios";
import zhCN from 'ant-design-vue/es/locale/zh_CN';

import {Form, message} from 'ant-design-vue';

const columns = [{
    dataIndex: 'name',
    key: 'name',
    title: "名称"
  }, {
    title: '父分类',
    dataIndex: 'parent',
    key: 'parent',
  }, {
    title: '顺序',
    dataIndex: 'sort',
    key: 'sort',
  }, {
    title: 'Action',
    key: 'action',
  }];


export default {
  name: "admin-category",
  components: {
    SmileOutlined,
    DownOutlined,
    QuestionCircleOutlined
  },
  setup() {
    // 初始化表格
    const categorys = ref([]);
    const searchOptions = ref([]);
    const loading = ref(true);

    // 获取表格数据
    const get = () => {
      const params = {
      }

      if (searchValue.value){
        params.name = searchValue.value
      }
      axios.get("/category/all", {params}).then( (res) => {
        let data = res.data;
        if (data.code == 200){

          loading.value = false;

          categorys.value = data.data;

          searchOptions.value = JSON.parse(JSON.stringify(data.data));

          searchOptions.value.unshift({name: '无', id: '0'});
          searchLoading.value = false;
        }
      });
    }

    function tree(parentId, list){
        const children = [];

        for (let c of list){
           if (c.parent == parentId){
             children.push(c);
             c.children = tree(c.id, list);
           }
        }
        return children;
    }

    // 新增
    const visible = ref(false);
    const title = ref('新增分类');
    const category = ref({});
    const rules = {
      name: [{
        required: true,
        message: '请输入分类名称',
        trigger: 'blur'
      }],
      // 省略校验规则
    };;


    const add = () => {
      title.value = "新增分类";
      category.value = {};
      visible.value = true;
    }

    const edit = (record) => {
      title.value = "编辑分类信息";
      console.log(record.id);
      category.value = JSON.parse(JSON.stringify(record));
      visible.value = true;
    }

    const handleOk = (e) => {
      axios.post('/category', category.value).then( (res) => {
          if (res.data.code == 200){
            let msg = "保存成功";
            if (category.value.id){
              msg = "修改信息成功";
            }
            // 保存成功
            message.success(msg);

            // 表格数据的刷新， 回显
            get();

            // 清空表单数据
            category.value = {};
          } else {
            // 保存失败
            message.error(res.data.message);
          }
        visible.value = false;
      })
    }

    // 删除信息
    const remove = (id) => {
      axios.delete('/category/' + id).then((res) => {
        if (res.data.code == 200){
          message.success("删除成功");
          // 表格数据的刷新， 回显
          get();
        } else{
          message.error(res.data.message);
        }
      });
    }

    // 搜索
    const searchValue = ref("");
    const searchLoading = ref(false);

    const search = () =>{
      searchLoading.value = true;
      get();
    }

    const filterOption = (input, option) => {
      return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };

    return {
      categorys,
      columns,
      get,
      loading,
      zhCN,
      visible,
      title,
      add,
      category,
      rules,
      handleOk,
      edit,
      remove,
      searchValue,
      searchLoading,
      search,
      filterOption,
      searchOptions
    };
  },
  mounted() {
    this.get();
  }
}
</script>

<style scoped>
.cover{
  width: 80px;
  height: 80px;
}
</style>